package info.fqtech.lingdemo.json;

import bean.SampleBean;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class JsonObjectSample {

    public static void main(String[] args){
        JsonObjectSample jos=new JsonObjectSample();
        jos.creatJsonByJsonObject();
        jos.creatJsonByMap();
        jos.creatJsonByBean();

    }
    //使用JSONObject的put方法添加JSON对象
    public void creatJsonByJsonObject(){
        JSONObject wx=new JSONObject();
        Object nullObj=null;
        try {
            wx.put("name","王小二");
            wx.put("age","26.5");
            wx.put("birthday","1990-9-9");
            wx.put("major",new String[]{"理发","数学"});
            wx.put("has_house",false);
            //直接传入null会报错
            wx.put("car",nullObj);
            System.out.println(wx.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //使用Map方法添加JSON对象
    public void creatJsonByMap(){
        Map<String,Object> wx=new HashMap<String,Object>();
        Object nullObj=null;
        wx.put("name","王小二");
        wx.put("age","26.5");
        wx.put("birthday","1990-9-9");
        wx.put("major",new String[]{"理发","数学"});
        wx.put("has_house",false);
        wx.put("car",nullObj);
        System.out.println(new JSONObject(wx).toString());
    }

    //使用javaBean方法添加JSON对象

    public void creatJsonByBean(){
        SampleBean sb=new SampleBean();
        sb.setName("王小二");
        sb.setAge(26.6);
        sb.setBirthday("1990-9-10");
        sb.setHouse(null);
        sb.setHas_car(false);
        sb.setSchool("蓝翔");
        sb.setMajor(new String[]{"理发","数学"});
        System.out.println(new JSONObject(sb));
        System.out.println("——————GJson——————");
        //使用Gson将sb对象转换为JSON
        Gson gson=new Gson();
        System.out.println(gson.toJson(sb));
        //使用GsonBuilder,格式为标准的Json，美化输出
        GsonBuilder gsonBuilder=new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson1=gsonBuilder.create();
        System.out.println(gson1.toJson(sb));
        //fastJson
        System.out.println("——————fastJson——————");
        String fastJsonStr= JSON.toJSONString(sb);
        System.out.println(fastJsonStr);

    }

}
